package com.itlong.cloud.intercept.sdkV1;

import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.sdk.DeveloperAuthSafeSettingsVO;
import com.itlong.cloud.enumerate.ecode.SDKErrorCodeEnum;
import com.itlong.cloud.user.sdk.ISDKServerOldUserServiceClient;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <desc>
 *      SDK开发者访问安全授权拦截器
 * </desc>
 *
 * @createDate 2018/12/19
 */
@Aspect
@Component
public class DeveloperAuthIntercept {

    private static Logger LOG = LoggerFactory.getLogger(DeveloperAuthIntercept.class);

    // 定义一个切入点
    @Pointcut("execution(* com.itlong.cloud.controller.sdkV1.cloud.intercom.server..*.*(..))")
    public void excudeService(){}

    @Autowired
    ISDKServerOldUserServiceClient iSDKUserServiceClient;

    /**
     * <desc>
     *      SDK开发者访问安全授权拦截器
     * </desc>
     *
     * @param thisJoinPoint
     * @author wangzhi
     * @createDate 2018/12/19
     */
    @Around("excudeService()")
    public Object twiceAsOld(ProceedingJoinPoint thisJoinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = HttpProtocolUtil.getIpAddr(request);
        //LOG.info("请求者IP为：" + ip);
        String appId=request.getParameter("appId");
        DeveloperAuthSafeSettingsVO developerAuthSafeSettingsVO = iSDKUserServiceClient.getSafeSettings(appId);
        List<String> bindingIps = null;
        List<String> bindingMacs = null;
        if (developerAuthSafeSettingsVO != null) {
            bindingIps = developerAuthSafeSettingsVO.getBindingIp();
            bindingMacs = developerAuthSafeSettingsVO.getBindingMac();
        }

        // 获取mac地址
//        String macAddress = null;

        if (bindingIps == null || !bindingIps.contains(ip)) {
            return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_IP_BINDING_ERR.getErrorCode());
        }
//        if (bindingMacs == null || !bindingMacs.contains(macAddress)) {
//            return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_MAC_BINDING_ERR.getErrorCode());
//        }
        return thisJoinPoint.proceed();
    }

}
